package com.atguigu.order.service.impl;

import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.order.bean.Order;
import com.atguigu.order.feign.ProductFeignClient;
import com.atguigu.order.service.OrderService;
import com.atguigu.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @author fhs
 * Create by 2025/6/23 09:47
 */
//那里发请求了，就用Slf4j记录一下
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    DiscoveryClient discoveryClient;
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    ProductFeignClient productFeignClient;

    // 实现负载均衡功能
    @Autowired
    LoadBalancerClient loadBalancerClient;

    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Long productId, Long userId) {
        Product product = getProductFormRemoteWithLoadBalanceAnnotation(productId);
        Order order = new Order();
        order.setId(1L);

        //总金额
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setAddress("比奇堡");
        //远程查询商品列表
        order.setProductList(Arrays.asList(product));

        return order;
    }

    //blockHandler兜底回调
    public Order createOrderFallback(Long productId, Long userId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(userId);
        order.setNickName("zhangsan");
        order.setAddress("尚硅谷");

        return order;
    }

    //4、使用OpenFeign进行远程调用，Openfeign本身有负载均衡功能
    private Product getProductFormRemoteWithLoadBalanceAnnotation(Long productId) {
        //使用Feign完成远程调用
        Product product = productFeignClient.getProduct(productId);
        return product;
    }

    //3、进阶3：基于注解的负载均衡
    //在OrderConfig的RestTemplate中添加@LoadBalanced
    private Product getProductFormRemoteWithLoadBalanceAnnotation1(Long productId) {
        //1、获取到商品
        //远程的url地址
        String url = "http://service-product/product/" + productId;

        //2、给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }


    //2、进阶：完成负载均衡发送请求
    private Product getProductFormRemote2(Long productId) {
        //1、获取到商品

        ServiceInstance instance = loadBalancerClient.choose("service-product");

        //http://localhost:9002/product/4
        //远程的url地址
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;

        //2、给远程发送请求
        log.info("远程请求:{}", url);
        //getForObject 会获取一个json格式的对象，转成商品类型

        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    //远程获取到商品服务
    //1、最初发现服务开始
    private Product getProductFormRemoteWithLoadBalance(Long productId) {
        //1、获取到商品
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");

        ServiceInstance instance = instances.get(0);
        //http://localhost:9002/product/4
        //远程的url地址
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;

        //2、给远程发送请求
        log.info("远程请求:{}", url);
        //getForObject 会获取一个json格式的对象，转成商品类型

        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }


}
